import json
import os
import shutil

import facade
from xjlibrary.mdatetime.mtime import getTodayDate
from xjlibrary.mdatetime.mtime2 import MDateTimeUtils
from xjlibrary.our_file_dir import BaseDir

from id_encode import GetLngid

curPath = BaseDir.get_file_dir_absolute(__file__)
logger = facade.get_streamlogger()
topPath = BaseDir.get_upper_dir(curPath, -2)
db3Path = BaseDir.get_new_path(topPath, "download", "adks_cqjd", "download", "db3")
BaseDir.create_dir(db3Path)
temp_db3 = os.path.join(curPath, "zt_template", "zt_template.db3")
configfile = BaseDir.get_new_path(curPath, "db.ini")


class ParaDB3(object):
    def __init__(self):
        self.logger = facade.get_streamlogger()
        self.new_db3_path = self.copyTempDB3(temp_db3, db3Path)
        self.dbsqlutils = facade.Sqlite3Utiles(logger=logger).Sqlite3DBConnectFromFilePath(
            self.new_db3_path, encoding="utf-8")
        self.mysqlutiles = facade.MysqlUtiles(configfile, "db", logger=self.logger)

    def copyTempDB3(self, temp_path, copy_out):
        """
        拷贝创建新的db3文件
        :param temp_path: 模板db3文件路径
        :param copy_out: 新的db3输出路径
        :return: 新db3路径
        """
        today_str = str(getTodayDate())
        if not os.path.isfile(temp_path) or not os.path.isdir(copy_out):
            raise FileNotFoundError
        new_db3_name = 'mirrorcqjtuadksvideo_' + today_str + '.db3'
        new_db3_path = os.path.join(copy_out, new_db3_name)
        shutil.copyfile(temp_path, new_db3_path)
        return new_db3_path

    def para(self):
        sql = "select rawid,url,vidmsg,authormsg,coverstat from article where stat=1"
        rows = self.mysqlutiles.SelectFromDB(sql)
        Listdata = []
        for row in rows:
            dicts = json.loads(row[2])
            # 标题
            title = dicts["title"]
            # 作者
            creator = dicts["author"].strip()
            if creator == "解说":
                creator = ""
            # 分类
            provider_subject = dicts["subject"]
            # 时间
            date_created = dicts["pub_time"].replace("/", "")
            date = date_created[:4]
            description = dicts["abstract"]
            url = "http://202.202.244.23" + dicts["href"].split("?")[0]+"?"+dicts["href"].split("&")[-1]
            rawid = row[0]
            # 导师简介
            creator_bio = row[3].strip()
            if creator_bio == "暂无":
                creator_bio = ""
            cover = row[4]
            if cover == 1:
                print("********************")
                cover = "/smartlib/mirrorcqjtuadksvideo/" + rawid + ".jpg"
            else:
                cover = ""
            provider = "mirrorcqjtuadksvideo"
            sub_db_id = "00082"
            lngid = GetLngid(sub_db_id, rawid)
            provider_id = provider + "@" + rawid
            provider_url = provider + "@" + url
            type_ = '10'
            language = 'ZH'
            country = 'CN'
            product = "ADKSDMT"
            sub_db = "CQJTU"
            provider_a = "BJADKS"
            strings = ""
            for key in dicts["dictsarticle"]:
                strings = strings + dicts["dictsarticle"][key] + ";"
            if strings:
                strings = strings.strip(";")
            description_unit = strings
            if description_unit == "立即播放":
                description_unit = ""
            batch = MDateTimeUtils.get_today_date_strings() + "00"
            Listdata.append((lngid, rawid, title, creator, provider_subject, date_created, date, description, creator_bio, cover,
                       provider, provider_id, provider_url, type_, language, country, description_unit, batch))
            if len(Listdata) > 1000:
                sql = "insert or ignore into modify_title_info_zt (`lngid`,`rawid`,`title`,`creator`,`provider_subject`,`date_created`,`date`,`description`,`creator_bio`,`cover`,`provider`,`provider_id`,`provider_url`,`type`,`language`,`country`,`description_unit`,`batch`) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
                self.dbsqlutils.ExeSqlliteMany(sql, Listdata)
                Listdata.clear()

        if len(Listdata) > 0:
            sql = "insert or ignore into modify_title_info_zt (`lngid`,`rawid`,`title`,`creator`,`subject_dsa`,`date_created`,`date`,`description`,`creator_bio`,`cover`,`provider`,`provider_id`,`provider_url`,`type`,`language`,`country`,`description_unit`,`batch`) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
            self.dbsqlutils.ExeSqlliteMany(sql, Listdata)


if __name__ == "__main__":
    para = ParaDB3()
    para.para()
